/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.hymnal.church;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;


public class HymnsNetReader {
    /**
     * Proxy settings.
     */
    static final String proxyAddress = "www-proxy.ru.oracle.com";
    static final int proxyPort = 80;
    static Proxy proxy;
    static final class SearchStrings {
        final static String baseURL = "http://hymnal.net/hymn.php/h/";
        final static String serchStr1 = "http://www.hymnal.net/Hymns/Hymnal/midi/e";
        final static String serchStr2 = "http://www.hymnal.net/Hymns/Hymnal/verbatim/e";
        final static String searchTuneStr1 = "/f=tune";
        final static String searchTuneStr1Post = "/f=tune";
    }
    public static Proxy getProxy(String proxyAddr, int port) throws IOException {
        SocketAddress addr = new InetSocketAddress(proxyAddr, port);
        return new Proxy(Proxy.Type.HTTP, addr);
    }

    static public void saveAllMidiFiles(String midiFolder, String tuneFolder) {
        int count = TableManager.getItemsCount();        
        for (int i = 1; i <= count; i++) {
            TableManager.TableItem item = (TableManager.TableItem) TableManager.getItem(i);
            HymnsNetReader.getHymnFileName(i, item);
            System.out.println(item);
            HymnsNetReader.saveMidiFile(item.melodyFileNameUrl, midiFolder, item.melodyFileName);
            HymnsNetReader.saveMidiFile(item.melodyTuneFileNameUrl, tuneFolder, item.melodyTuneFileName);
        }
    }

    static private void saveMidiFile(String urlName, String folder, String fileName) {

        try {            
            URL url = new URL(urlName);
            HttpURLConnection httpConnection;
            if (proxy != null) {
                httpConnection = (HttpURLConnection) url.openConnection(proxy);
            } else {
                httpConnection = (HttpURLConnection) url.openConnection();
            }
            byte bytes[] = new byte[100];
            InputStream is = httpConnection.getInputStream();


            File f = new File(folder + fileName);
            FileOutputStream fos = new FileOutputStream(f);

            int readResult;
            while ((readResult = is.read(bytes)) > 0) {
                fos.write(bytes, 0, readResult);
            }
        } catch (IOException ioe) {
            System.out.println("saveMidiFile ioe:" + ioe.getMessage());
        }

    }
    
    
    
    static void getHymnFileName(int ruNumber, TableManager.TableItem item) {
        int num = item.englishNum;
        
        try {                        
            String urlStr = SearchStrings.baseURL + num;
            URL url = new URL(urlStr);
            HttpURLConnection httpConnection;
            if (proxy != null) {
                httpConnection = (HttpURLConnection) url.openConnection(proxy);
            } else {
                httpConnection = (HttpURLConnection) url.openConnection();
            }
            InputStream is = httpConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                //System.out.println(line);
                int index = line.indexOf(SearchStrings.serchStr1);
                int strLen = SearchStrings.serchStr1.length();
                if (index == -1) {
                    index = line.indexOf(SearchStrings.serchStr2);
                    strLen = SearchStrings.serchStr2.length();
                }

                if (index >= 0) {
                    int subIndex = line.indexOf("';");
                    item.melodyFileNameUrl = line.substring(index, subIndex);
                    item.melodyFileName = line.substring(index + strLen - 1, subIndex);
                    System.out.println(item.melodyFileNameUrl);
                    System.out.println(item.melodyFileName);                    
                    continue;
                }
                index = line.indexOf(SearchStrings.searchTuneStr1);
                if (index != -1) {
                    int indexHTTP = line.lastIndexOf("http://", index);
                    int subIndex = line.indexOf("\">", index);
                    
                    strLen = SearchStrings.searchTuneStr1.length();                                        
                    item.melodyTuneFileName = "tune_" + ruNumber + ".midi";                    
                    item.melodyTuneFileNameUrl = line.substring(indexHTTP, subIndex);                    
                }
                if (item.melodyFileName != null && item.melodyTuneFileNameUrl != null) {
                    br.close();
                    httpConnection.disconnect();
                    break;
                }
            }
        } catch (IOException ioe) {
            System.out.println("ioe:" + ioe.getMessage());
        }
    }
    static {
        /*
        try {        
            proxy = getProxy(proxyAddress, proxyPort);
        } catch (IOException ex) {
            System.out.println("Proxy not found:" + proxyAddress + ", port:" + proxyPort);
        }
                */
    }
}
